package com.practice.communication.aio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.CountDownLatch;

public class ClientAsyncHandler implements Runnable, CompletionHandler<Void, ClientAsyncHandler> {
	
	private AsynchronousSocketChannel clientChannel;
	private String ip;
	private int port;
	private CountDownLatch latch;

	public ClientAsyncHandler(String ip, int port) {
		this.ip = ip;
		this.port = port;
		
		try {
			//创建异步的客户端通道
			clientChannel = AsynchronousSocketChannel.open();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public void run() {
		//创建CountDwonLatch等待
		latch = new CountDownLatch(1);
		
		//发起异步连接操作，回调参数就是这个类本身，如果连接成功会回调completed方法
		clientChannel.connect(new InetSocketAddress(ip, port), this, this);
		
		try {
			latch.await();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		try {
			clientChannel.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	//连接服务器成功，意味着TCP三次握手完成
	@Override
	public void completed(Void result, ClientAsyncHandler attachment) {
		System.out.println("客户端成功连接到服务器...");
	}

	@Override
	public void failed(Throwable exc, ClientAsyncHandler attachment) {
		System.out.println("连接服务器失败");
		exc.printStackTrace();
		
		try {
			clientChannel.close();
			latch.countDown();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void sendMsg(String msg) {
		byte[] bytes = msg.getBytes();
		ByteBuffer writeBuffer = ByteBuffer.allocate(bytes.length);
		writeBuffer.put(bytes);
		writeBuffer.flip();
		
		clientChannel.write(writeBuffer, writeBuffer, new ClientWriteHandler(clientChannel, latch));
	}

}
